#include "MonitoringRealData.h"
#include "ui_MonitoringRealData.h"
#include <QTimer>
#include "SnaillTcpClient.h"
#include <QObject>
#include "wareRecodeModel.h"
MonitoringRealData::MonitoringRealData(QWidget *parent,deviceModel*deviceModel,userModel*userModel) :
    QWidget(parent),
    ui(new Ui::MonitoringRealData),
    dModel(deviceModel),
    uModel(userModel),
    tabModel(this)

{
    ui->setupUi(this);
    setWindowFlags(windowFlags() | Qt::WindowCloseButtonHint); // 确保有关闭按钮
    setAttribute(Qt::WA_DeleteOnClose, true); // 设置关闭时删除对象

    ui->tableView->setModel(&tabModel);
    dev_id = dModel->id;
    isRole=false;
    m_port=new QSerialPort;
    isOpen=false;
    connect(SnaillTcpClient::instance(), &SnaillTcpClient::dataReceived, this, &MonitoringRealData::handleDataReceived);
    connect(ui->pushButton,&QPushButton::clicked,this,&MonitoringRealData::openSerial);
    p_dataThread=nullptr;
    p_warnThread=nullptr;
     p_chart=new MonitoringChart(this);
    ui->horizontalLayout_3->addWidget(p_chart);

}


void MonitoringRealData::showEvent(QShowEvent *event)
{
    qDebug() << "页面显示，进入页面操作可在此处添加";
    QJsonObject jsonObj;
    jsonObj["action"] ="getwarnrole";
    jsonObj["device_id"] =dev_id;
    if (SnaillTcpClient::instance()->sendJsonData(jsonObj)) {
        qDebug() << "deviceList data sent successfully";

    } else {

        return ;
    }
    QWidget::showEvent(event);
}
void MonitoringRealData::openSerial()
{
    if(!isOpen){

        m_port->setPortName("COM7");

        qint32 baudRate = 9600;
        m_port->setBaudRate(baudRate);

        m_port->setDataBits(QSerialPort::DataBits::Data8);

        m_port->setParity(QSerialPort::Parity::NoParity);

        m_port->setStopBits(QSerialPort::StopBits::OneStop);

        m_port->setFlowControl(QSerialPort::FlowControl::NoFlowControl);

        if(m_port->open(QSerialPort::ReadWrite)){
            isOpen=true;
            ui->pushButton->setText("关闭串口");
            connect(m_port,&QSerialPort::readyRead,this,&MonitoringRealData::onReadData);
        }else {
            ui->pushButton->setText("打开串口失败");

        }

    }else {
        m_port->close();
        ui->pushButton->setText("打开串口");
        isOpen=false;
    }

}
void MonitoringRealData::onReadData()
{
    QByteArray buff=m_port->readAll();
    qDebug()<<"buff==="<<buff;
    if (buff.isEmpty()) {
            qDebug() << "Received data is empty.";
            return;
        }
    // 累积数据
       accumulatedData.append(buff);

       int startIndex = 0;
       while (startIndex < accumulatedData.size()) {
           int openBraceIndex = accumulatedData.indexOf('{', startIndex);
           if (openBraceIndex == -1) {
               // 没有找到起始的 {，退出循环
               break;
           }

           int braceCount = 1;
           int endIndex = openBraceIndex + 1;
           while (endIndex < accumulatedData.size()) {
               if (accumulatedData[endIndex] == '{') {
                   braceCount++;
               } else if (accumulatedData[endIndex] == '}') {
                   braceCount--;
                   if (braceCount == 0) {
                       // 找到完整的 JSON 数据
                       QByteArray jsonData = accumulatedData.mid(openBraceIndex, endIndex - openBraceIndex + 1);
                       qDebug() << "Received complete JSON data:" << jsonData;
                       getJson(jsonData);
                       startIndex = endIndex + 1;
                       break;
                   }
               }
               endIndex++;
           }

           if (braceCount != 0) {
               // 没有找到完整的 JSON 数据，等待更多数据
               break;
           }
       }

       // 移除已经处理过的数据
       accumulatedData = accumulatedData.mid(startIndex);

}

void MonitoringRealData::handleDataReceived(const QByteArray &data)
{
    qDebug()<<"MonitoringRealData::handleDataReceived"<<data;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
    QJsonObject jsonObj = jsonDoc.object();
    QString action = jsonObj["action"].toString();
    qDebug()<<"MonitoringRealData::handleDataReceived action"<<action;
    if(action=="getwarnrole"){
        qDebug()<<"进入了有数33"<<jsonObj;
        qDebug()<<"deviceList==="<<jsonObj;
        QString id = jsonObj["id"].toString();
        qDebug()<<"id======"<<id;
        if(id!="-1"){
            isRole=true;
            maxHemperature=jsonObj["maxHemperature"].toInt();
            maxTemperature=jsonObj["maxTemperature"].toInt();
            minHemperature=jsonObj["minHemperature"].toInt();
            minTemperature=jsonObj["minTemperature"].toInt();
        }
    }
}


MonitoringRealData::~MonitoringRealData()
{

    delete ui;
    if (m_port->isOpen()) {
            m_port->close();
        }


    qDebug()<<"定时器销毁了";
    if (p_dataThread) {
            QObject::disconnect(p_dataThread, &realDataThread::sendData, this, &MonitoringRealData::sendToData);
            p_dataThread->quit();
            p_dataThread->wait();
            delete p_dataThread;
            p_dataThread = nullptr;
        }
        if (p_warnThread) {
            QObject::disconnect(p_warnThread, &realWarnThread::sendWarn, this, &MonitoringRealData::sendToWarn);
            p_warnThread->quit();
            p_warnThread->wait();
            delete p_warnThread;
            p_warnThread = nullptr;
        }
    //    if (timer) {
    //        timer->stop();
    //        delete timer;
    //    }

}
void MonitoringRealData::sendToData(int temperature, int humidity, int light, int co2, int pressure)
{
    qDebug()<<"线程开始了"<<temperature<<humidity<<light;
    sendData(temperature,humidity,light,co2,pressure);
}

void MonitoringRealData::sendToWarn(int temperature, int humidity, int light, int co2, int pressure)
{
    if(temperature>maxTemperature){
        QString str="温度过高";
        QTimer::singleShot(100, [=]() {
            sendWran(str);
        });

    }
    if(temperature<minTemperature){
        QString str="温度过低";
        QTimer::singleShot(100, [=]() {
            sendWran(str);
        });

    }
    if(humidity>maximumHeight()){
        QString str="湿度过高";
        QTimer::singleShot(100, [=]() {
            sendWran(str);
        });
    }
    if(humidity<minimumHeight()){
        QString str="湿度过低";
        QTimer::singleShot(100, [=]() {
            sendWran(str);
        });
    }
}
void MonitoringRealData::sendDataToServer(int&temperature,int&humidity,int&light,int&co2,int&pressure)
{

     qDebug()<<"sendDataToServer线程开始了==="<<temperature<<humidity;
    if(p_dataThread==nullptr){
        p_dataThread=new realDataThread(temperature,humidity,light,co2,pressure);
        connect(p_dataThread,&realDataThread::sendData,this,&MonitoringRealData::sendToData);
    }
    p_dataThread->setData(temperature,humidity,light,co2,pressure);
    if(!p_dataThread->isRunning()){
        p_dataThread->start();
    }

  //  sendData(temperature,humidity,light,co2,pressure);

    qDebug()<<temperature<<humidity<<isRole;
    p_chart->sendChartData(temperature,humidity);

    if(isRole){
        if(p_warnThread==nullptr){
            p_warnThread=new realWarnThread(temperature,humidity,light,co2,pressure);
            connect(p_warnThread,&realWarnThread::sendWarn,this,&MonitoringRealData::sendToWarn);
        }
         p_warnThread->setData(temperature,humidity,light,co2,pressure);
        if(!p_warnThread->isRunning()){
            p_warnThread->start();
        }




    }

}

void MonitoringRealData::getJson(const QByteArray&buff)
{
    QJsonDocument jsonDoc = QJsonDocument::fromJson(buff);

    if (!jsonDoc.isNull() && jsonDoc.isObject()) {
            // 获取 JSON 对象
            QJsonObject jsonObj = jsonDoc.object();

            // 访问 JSON 对象中的字段
            if (jsonObj.contains("humidity") && jsonObj.contains("temperature")) {
                int humidity = jsonObj["humidity"].toInt();
                int temperature = jsonObj["temperature"].toInt();
                int light = 32;
                int co2 = 22;
                int pressure = 11;
                qDebug()<<"获取到的温湿度数据"<<temperature<<humidity;
                // 调用发送数据的函数
                sendDataToServer(temperature, humidity, light, co2, pressure);
            } else {
                qDebug() << "JSON object does not contain required fields.";
            }
        } else {
            qDebug() << "JSON 解析失败";
        }
}
void MonitoringRealData::sendData(int&temperature,int&humidity,int&light,int&co2,int&pressure){

    MonitoringDataModel data;
    data.user_id =  QString::number(uModel->id);
    data.device_id = dev_id;
    data.temperature =  QString::number(temperature);
    data.humidity =  QString::number(humidity);
    data.light =  QString::number(light);
    data.co2 =  QString::number(co2);
    data.pressure =  QString::number(pressure);
    dataList.append(data);
    tabModel.updateAllDeviceList(dataList);
    QJsonObject jsonObj;
    jsonObj["action"] ="realdata";
    jsonObj["user_id"] =data.user_id;
    jsonObj["device_id"] =data.device_id;
    jsonObj["temperature"] =data.temperature;
    jsonObj["humidity"] =data.humidity;
    jsonObj["light"] =data.light;
    jsonObj["co2"] =data.co2;
    jsonObj["pressure"] =data.pressure;
    if (SnaillTcpClient::instance()->sendJsonData(jsonObj)) {
        //  qDebug() << "deviceList data sent successfully";
    } else {

        return ;
    }
}

void MonitoringRealData::sendWran(const QString&content)
{

    LOG_INFO("警告"+dev_id+content);
    QJsonObject jsonObjrecode;
    jsonObjrecode["action"] ="warnrecode";
    jsonObjrecode["device_id"] =dev_id;
    jsonObjrecode["content"] =content;
    jsonObjrecode["status"] ="未处理";
    jsonObjrecode["note"] ="马上处理";
    if (SnaillTcpClient::instance()->sendJsonData(jsonObjrecode)) {
        //  qDebug() << "deviceList data sent successfully";
    } else {

        return ;
    }
}



